//
//  RequestError.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/20.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit
import Moya
import RxSwift

struct RequestError: Swift.Error {
    var code : Int = 0
    var msg : String = ""
    
    init(code: Int, msg: String) {
        self.code = code
        self.msg = msg
    }
}

extension RequestError: LocalizedError {
    
    public var errorDescription: String? {
        return self.msg
    }
    
    var localizedDescription: String {
        return self.msg
    }
}

extension Response {
    
    public func errorWhenCodeNot200() throws -> Response {
        if code == 200 {
            return self
        }
        throw RequestError.init(code: code, msg: msg)
    }
    
}

extension ObservableType where Element == Response {
    
    public func errorWhenCodeNot200() -> Observable<Response> {
        return flatMap { response -> Observable<Response> in
            return Observable.just(try response.errorWhenCodeNot200())
        }
    }
    
}

extension PrimitiveSequence where Trait == SingleTrait, Element == Response {
    
    public func errorWhenCodeNot200() -> Observable<Response>{
        return self.asObservable().errorWhenCodeNot200()
    }
    
}
